import { useState } from 'react';
import useSWR from 'swr';
import { Select, Descriptions, Spin, Divider } from 'antd';
import { switchesFetcher } from '../services/switches';
import { flowFetcher } from '../services/flow';
import Layout from '../components/Layout';

const { Option } = Select;

const useData = () => {
  const [select, setSelect] = useState('1');

  const { data: switchesData } = useSWR('/stats/switches', switchesFetcher);

  const { data: flowData } = useSWR(['/stats/flow', select], (_, temp) => flowFetcher(temp));

  return {
    isLoading: !flowData || !switchesData,
    data: { switchesData, flowData },
    select,
    setSelect,
  };
};

export default function Home() {
  const { isLoading, data, select, setSelect } = useData();

  let element = <Spin />;

  if (!isLoading) {
    const { flowData } = data;
    const realData = flowData[select][0];

    element = (
      <>
        <Select
          defaultValue={select}
          style={{ width: 120 }}
          onChange={e => {
            setSelect(e);
          }}>
          {data.switchesData.map(item => {
            return (
              <Option key={item} value={item}>
                {item}
              </Option>
            );
          })}
        </Select>
        <Divider />
        <Descriptions title="流表信息" bordered>
          <Descriptions.Item label="Actions">{realData.actions.join(',')}</Descriptions.Item>
          <Descriptions.Item label="ByteCount">{realData['byte_count']}</Descriptions.Item>
          <Descriptions.Item label="Cookie">{realData.cookie}</Descriptions.Item>

          <Descriptions.Item label="DurationNsec">{realData['duration_nsec']}</Descriptions.Item>
          <Descriptions.Item label="DurationSec" span={2}>
            {realData['duration_sec']}
          </Descriptions.Item>

          <Descriptions.Item label="Flags">{realData.flags}</Descriptions.Item>
          <Descriptions.Item label="HardTimeout">{realData['hard_timeout']}</Descriptions.Item>
          <Descriptions.Item label="IDLETimeout">{realData['idle_timeout']}</Descriptions.Item>
          <Descriptions.Item label="Other">
            length: {realData.length}
            <br />
            packet_count: {realData['packet_count']}
            <br />
            priority: {realData['priority']}
            <br />
            table_id: {realData['table_id']}
            <br />
          </Descriptions.Item>
        </Descriptions>
      </>
    );
  }

  return <Layout>{element}</Layout>;
}
